package com.yx.cloud.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iot.base.bean.message.IotMessage;
import com.iot.common.utils.LogUtils;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.yx.cloud.R;
import com.yx.cloud.utils.RomUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class MessageAdapter extends BaseAdapter {
    private static final String TAG = "MessageAdapter";
    private Context mContext;
    private List<IotMessage> mMessageList;
    private List<Boolean> selectList;
    private boolean isEdit = false;
    private boolean enableSwipeDelete = false;
    private ItemListener itemListener;
    private Map<String, Bitmap> iconMap;
    private SimpleDateFormat simpleDateFormat;
    private boolean showArrow = true;

    public MessageAdapter(Context context, List<IotMessage> mMessageList) {
        this.mContext = context;
        this.iconMap = new ConcurrentHashMap<>();
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        updateMessage(mMessageList);
    }

    public void showRightArrow(boolean showArrow) {
        this.showArrow = showArrow;
    }

    public void setItemListener(ItemListener itemListener) {
        this.itemListener = itemListener;
    }

    public void updateMessage(List<IotMessage> messageList) {
        mMessageList = messageList;
        selectList = new ArrayList<>(messageList.size());
        notifyDataSetChanged();

    }

    public void addMessage(List<IotMessage> messageList) {
        mMessageList.addAll(messageList);
        for (int i = 0; i < messageList.size(); i++) {
            selectList.add(false);
        }
        notifyDataSetChanged();
    }

    public List<IotMessage> getSelectedMessages() {
        List<IotMessage> messages = new ArrayList<>();
        for (int i = 0; i < selectList.size(); i++) {
            if (selectList.get(i)) {
                messages.add(mMessageList.get(i));
            }
        }
        return messages;
    }

    public List<IotMessage> getMessageList() {
        return mMessageList;
    }

    public void pickAll(boolean isPick) {
        for (int i = 0; i < selectList.size(); i++) {
            selectList.set(i, isPick);
        }
        notifyDataSetChanged();
    }

    public boolean isAllSelected() {
        for (int i = 0; i < selectList.size(); i++) {
            if (!selectList.get(i)) {
                return false;
            }
        }
        return true;
    }

    public void editMode(boolean isEdit) {
        this.isEdit = isEdit;
        notifyDataSetChanged();
    }

    public void setEnableSwipeDelete(boolean enableSwipeDelete) {
        this.enableSwipeDelete = enableSwipeDelete;
    }

    public boolean isEditMode() {
        return isEdit;
    }


    @Override
    public int getCount() {
        return mMessageList.size();
    }

    @Override
    public IotMessage getItem(int position) {
        return mMessageList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        ViewHolder mHolder;
        if (convertView == null) {
            convertView = View.inflate(mContext, R.layout.message_item_01, null);
            mHolder = new ViewHolder();
            mHolder.mContainer = convertView.findViewById(R.id.rl_messageContainer);
            mHolder.swipeMenuLayout = convertView.findViewById(R.id.sml_message_item);
            mHolder.mSelect = convertView.findViewById(R.id.cbx_select_message);
            mHolder.mTitle = convertView.findViewById(R.id.tv_message_type);
            mHolder.mDelete = convertView.findViewById(R.id.btn_message_delete_item);
            mHolder.hasRead = convertView.findViewById(R.id.iv_item_not_read);
            mHolder.mTvMessageTime = convertView.findViewById(R.id.tv_messageTime);
            mHolder.mTvMessageContent = convertView.findViewById(R.id.tv_messageContent);
            mHolder.mRobotIcon = convertView.findViewById(R.id.iv_robot_icon);
            mHolder.ivRightArrow = convertView.findViewById(R.id.iv_item_right_arrow);
            convertView.setTag(mHolder);
        } else {
            mHolder = (ViewHolder) convertView.getTag();
        }
        IotMessage bean = mMessageList.get(position);
        mHolder.mRobotIcon.setImageResource(R.mipmap.robot_fault);
        String content = bean.getContent();
        if (TextUtils.isEmpty(content)) {
            mHolder.mTitle.setText("");
        } else {
            mHolder.mTitle.setText(content);
        }

        mHolder.ivRightArrow.setVisibility(showArrow ? View.VISIBLE : View.GONE);

        mHolder.mTvMessageTime.setText(simpleDateFormat.format(new Date(bean.getTime())));
//        mHolder.mTvMessageContent.setText(bean.getContent());
        mHolder.mContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                if (isEdit) {
                    mHolder.mSelect.performClick();
                } else {
                    bean.setRead(false);
                    notifyDataSetChanged();
                    if (itemListener != null) {
                        itemListener.onItemClick(position);
                    }
                }
            }
        });
        mHolder.mDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                if (itemListener != null) {
                    itemListener.onItemDelete(position);
                    mHolder.swipeMenuLayout.quickClose();
                }
            }
        });
        mHolder.swipeMenuLayout.setSwipeEnable(enableSwipeDelete);


        //编辑模式下的选择框
        if (isEdit) {
            mHolder.mSelect.setVisibility(View.VISIBLE);
            mHolder.mSelect.setChecked(selectList.get(position));
            mHolder.mSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    selectList.set(position, isChecked);
                    itemListener.onItemCheckChanged(isChecked);
                }
            });
        } else {
            mHolder.mSelect.setVisibility(View.GONE);
        }

        mHolder.hasRead.setVisibility(bean.isRead() ? View.VISIBLE : View.GONE);

        return convertView;
    }

    @SuppressLint("StaticFieldLeak")
    private void asyncloadImage(Set<String> uriSet) {
        iconMap.clear();
        LogUtils.i("load image size : " + iconMap.size());
        AsyncTask<String, Void, Void> asyncTask = new AsyncTask<String, Void, Void>() {
            @Override
            protected Void doInBackground(String... uriArray) {
                try {
                    //这个URI是图片下载到本地后的缓存目录中的URI
                    for (int i = 0; i < uriArray.length; i++) {
                        Bitmap bitmap = getLocalOrNetBitmap(uriArray[i]);
                        iconMap.put(uriArray[i], bitmap);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void v) {
                LogUtils.i("load image size1 : " + iconMap.size());
                notifyDataSetChanged();
            }
        };
        if (uriSet.size() != 0) {
            String[] uriArray = new String[uriSet.size()];
            uriSet.toArray(uriArray);
            asyncTask.execute(uriArray);
        }
    }

    /**
     * @param url 　本地或网络的url
     * @return　url的bitmap
     */
    public Bitmap getLocalOrNetBitmap(String url) {
        Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.headportrait_icon);
        if (url != null) {
            InputStream in = null;
            BufferedOutputStream out = null;
            try {
                //读取图片输入流
                in = new BufferedInputStream(new URL(url).openStream(), 2 * 1024);
                //准备输出流
                final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                out = new BufferedOutputStream(dataStream, 2 * 1024);
                byte[] b = new byte[1024];
                int read;
                //将输入流变为输出流
                while ((read = in.read(b)) != -1) {
                    out.write(b, 0, read);
                }
                out.flush();
                //将输出流转换为bitmap
                byte[] data = dataStream.toByteArray();
                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                data = null;
                return bitmap;
            } catch (IOException e) {
                e.printStackTrace();
                return bitmap;
            }
        }
        return bitmap;
    }

    public interface DeviceCallback {
        void onAccept(IotMessage IotMessage);

        void onReject(IotMessage IotMessage);
    }

    public interface ItemListener {
        void onItemClick(int position);

        void onItemDelete(int position);

        void onItemCheckChanged(boolean isCheck);
    }

    class ViewHolder {
        RelativeLayout mContainer;
        SwipeMenuLayout swipeMenuLayout;
        CheckBox mSelect;
        TextView mTitle;
        TextView mTvMessageTime;
        TextView mTvMessageContent;
        TextView mDelete;
        ImageView hasRead;
        ImageView mRobotIcon;
        ImageView ivRightArrow;
    }
}
